/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package exatrez.manager;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.wideplay.warp.persist.Transactional;
import exatrez.dao.SeqNumDAO;
import exatrez.model.SeqNum;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 *
 * @author fikri
 */
public class SequenceManager {

    @Inject
    protected com.google.inject.Provider<Session> sessionProvider;
    @Inject
    private SeqNumDAO seqNumDAO;
    @Inject
    Provider<SessionFactory> sp;
    
    private static Logger LOG = LoggerFactory.getLogger(SequenceManager.class);

    public String getSequence(String id) {
        int seq = 0;
        Session session = sessionProvider.get();
        Query query = session.createQuery(
                "select a.seqNo from SeqNum a "
                + "where a.seqName = :id");
        query.setParameter("id", id);
        
        if (query.list().isEmpty()) {
            seq = 1;
        } else {           
            seq = (Integer)query.iterate().next() + 1;            
        }
        SeqNum sequence = new SeqNum();
        sequence.setSeqName(id);
        sequence.setSeqNo(seq);
        updateSequece(sequence);
        return intToString(seq, 3);
    }
    
    public String getSequenceWithoutLeadingZero(String id) {
        Session session = sessionProvider.get();
        Query query = session.createQuery(
                "select a.seqNo from SeqNum a "
                + "where a.seqName = :id");
        query.setParameter("id", id);

        int seq = (Integer)query.iterate().next() + 1;
        return String.valueOf(seq);
    }

    @Transactional
    public void updateSequece(SeqNum seq) {
        int seqNo = seq.getSeqNo();
        if (seqNo == 999) {
            seq.setSeqNo(0);
        }
        seqNumDAO.saveOrUpdate(seq);
    }
    
    @Transactional
    public void updateCounter(SeqNum seq) {
        seqNumDAO.update(seq);
    }

    static String intToString(int num, int digits) {
        assert digits > 0 : "Invalid number of digits";

        // create variable length array of zeros
        char[] zeros = new char[digits];
        Arrays.fill(zeros, '0');
        // format number as String
        DecimalFormat df = new DecimalFormat(String.valueOf(zeros));

        return df.format(num);
    }
    
    
    public void resetSequence() {
        LOG.debug("reset sequence start");
        StatelessSession ss = null;
        Transaction tx = null;
        try {
            ss = sp.get().openStatelessSession();
            Query query = ss.createQuery("Select a from SeqNum a");
            
            List<SeqNum> list = query.list();
            if (!list.isEmpty()) {
                tx = ss.beginTransaction();
                for (SeqNum seq : list) {
                    seq.setSeqNo(0);
                    ss.update(seq);
                }
                tx.commit();
            }            
        } catch (Exception ex) {
            LOG.error("error {}", ex);
            if (tx !=null) tx.rollback();
        }finally{
            if (ss != null) {
                ss.close();
            }
        }
        LOG.debug("reset sequence finish");
    }
}
